// TcpClient.cpp
#include "tcpclient.h"
#include <QThread>
TcpClient::TcpClient(QObject *parent)
    : QObject(parent)
    , m_socket(nullptr)
{
    // 确保在正确的线程中创建和初始化 socket
    m_socket = new QTcpSocket();
    m_socket->moveToThread(this->thread());
    m_socket->setParent(this);

    // 使用 Qt::QueuedConnection 确保跨线程信号槽安全
    connect(m_socket, &QTcpSocket::connected, this, &TcpClient::handleConnected, Qt::QueuedConnection);
    connect(m_socket, &QTcpSocket::disconnected, this, &TcpClient::handleDisconnected, Qt::QueuedConnection);
    connect(m_socket, &QTcpSocket::readyRead, this, &TcpClient::handleReadyRead, Qt::QueuedConnection);
    connect(m_socket, QOverload<QAbstractSocket::SocketError>::of(&QAbstractSocket::error),
            this, &TcpClient::handleError, Qt::QueuedConnection);
}

TcpClient::~TcpClient()
{
    if (m_socket->state() == QAbstractSocket::ConnectedState) {
        m_socket->disconnectFromHost();
    }
}

void TcpClient::connectToServer(const QString& host, quint16 port)
{
    if (m_socket->state() == QAbstractSocket::ConnectedState) {
        return;
    }
    m_socket->connectToHost(host, port);
}

void TcpClient::sendData(const QJsonObject& data)
{
    if (m_socket->state() != QAbstractSocket::ConnectedState) {
        emit error("Not connected to server");
        return;
    }
    qDebug() << "服务器-当前线程ID:" << QThread::currentThreadId();// 打印主线程ID

    QJsonDocument doc(data);
    QByteArray jsonData = doc.toJson();
    m_socket->write(jsonData);
    m_socket->flush();
}

void TcpClient::disconnectFromServer()
{
    if (m_socket->state() == QAbstractSocket::ConnectedState) {
        m_socket->disconnectFromHost();
    }
}

bool TcpClient::isConnected() const
{
    return m_socket->state() == QAbstractSocket::ConnectedState;
}

void TcpClient::handleConnected()
{
    emit connected();
}

void TcpClient::handleDisconnected()
{
    emit disconnected();
}

void TcpClient::handleReadyRead()
{
    QByteArray data = m_socket->readAll();
    QJsonDocument doc = QJsonDocument::fromJson(data);
    if (!doc.isNull() && doc.isObject()) {
        emit dataReceived(doc.object());
    }
}

void TcpClient::handleError(QAbstractSocket::SocketError socketError)
{
    emit error(m_socket->errorString());
}
